#include <unistd.h>
#include <stdlib.h>
#include "halfcom.h"

int HALFCOM_Status = 0;

void HC_getData(int fuart, void(*callback)(unsigned char *,int))
{
	static unsigned char buf[256],HC_receiveBuffer[HALFCOM_BUFFERSIZE];
	static unsigned int index;
	int i,j,len;
	unsigned char cbits,dbits,crc;
	len = read(fuart, buf, 256);
	if(len < 1) return;
	if(len > 256) return;
	for(i=0;i<len;i++)
	{
		cbits = buf[i]&0xf0;
		dbits = buf[i]&0x0f;
		switch(cbits)
		{
		case HALFCOM_BEGIN:
			index = 0;
			break;
		case HALFCOM_HIGH:
			if(index >= HALFCOM_BUFFERSIZE) break;
			HC_receiveBuffer[index] = (dbits<<4);
			break;
		case HALFCOM_LOW:
			if(index >= HALFCOM_BUFFERSIZE) break;
			HC_receiveBuffer[index] |= dbits;
			index++;
			break;
		case HALFCOM_END:
			crc = 0;
			for(j=0;j<(index-1);j++)
			{
				crc += HC_receiveBuffer[j];
			}
			if(crc == HC_receiveBuffer[index-1])
			{
				crc = HALFCOM_DATAOK;
				write(fuart, &crc, 1);
				callback(HC_receiveBuffer,index-1);
			}
			else
			{
				crc = HALFCOM_DATAERROR;
				write(fuart, &crc, 1);
			}
			break;
		case HALFCOM_DATAOK:
			HALFCOM_Status = HALFCOM_DATAOK;
			break;
		case HALFCOM_DATAERROR:
			HALFCOM_Status = HALFCOM_DATAERROR;
			break;
		default:
			break;
		}
	}
}

void HC_sendData(int fuart, unsigned char *data, unsigned int length)
{
	unsigned int i;
	unsigned char *buf,crc=0;
	buf = (unsigned char*)malloc(length*2+4);
	HALFCOM_Status = 0;
	buf[0] = (HALFCOM_BEGIN);
	for(i=0;i<length;i++)
	{
		crc += data[i];
		buf[i*2+1] = (((data[i]>>4)&0x0f)|HALFCOM_HIGH);
		buf[i*2+2] = ((data[i]&0x0f)|HALFCOM_LOW);
	}
	buf[length*2+1] = (((crc>>4)&0x0f)|HALFCOM_HIGH);
	buf[length*2+2] = ((crc&0x0f)|HALFCOM_LOW);
	buf[length*2+3] = (HALFCOM_END);
	write(fuart, buf, length*2+4);
	free(buf);
}
